import { join } from 'path';
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, Like } from 'typeorm';
import { NoteContentData } from './dto/note-data.entity';
import { CommonResult, typeResult } from '../utils/result';
import { Comment } from './types';
import { unlinkSync } from 'fs';

@Injectable()
export class NoteService {
  constructor(
    @InjectRepository(NoteContentData)
    private readonly noteRepository: Repository<NoteContentData>,
  ) {}

  async getAllNoteList(
    userId: bigint,
    searchValue: string,
  ): Promise<typeResult<NoteContentData[]>> {
    let noteList = [];
    // 游客 为 0
    if ((userId as never) == '22') {
      noteList = await this.noteRepository.find({
        select: [
          'id',
          'title',
          'imageUrl',
          'text',
          'noteUsername',
          'like',
          'see',
          'createTime',
          'isPublic',
          'userId',
          'isTopping',
        ],
        order: { createTime: 'DESC' },
        where: {
          title: Like(`%${searchValue}%`),
        },
      });
    } else {
      noteList = await this.noteRepository.find({
        select: [
          'id',
          'title',
          'imageUrl',
          'text',
          'noteUsername',
          'isPublic',
          'like',
          'see',
          'createTime',
          'isTopping',
        ],
        order: { createTime: 'DESC' },
        where: {
          userId,
          title: Like(`%${searchValue}%`),
        },
      });
      const touristList = await this.noteRepository.find({
        select: [
          'id',
          'title',
          'imageUrl',
          'text',
          'noteUsername',
          'like',
          'isPublic',
          'see',
          'createTime',
          'isTopping',
        ],
        order: { createTime: 'DESC' },
        where: {
          userId: '0' as never,
          title: Like(`%${searchValue}%`),
        },
      });
      (userId as never) != '0' ? noteList.push(...touristList) : noteList;
    }

    if (noteList.length == 0) {
      return CommonResult([], true, 401, '没有找到文章');
    }
    return CommonResult(noteList, true, 200);
  }

  async createComment(note: Comment, user: any) {
    if (note.title == '' || note.content == '') {
      return CommonResult(null, true, 401, '没有提供 字段 或标题');
    }
    const noteContentData = new NoteContentData();
    noteContentData.like = 0;
    noteContentData.see = 0;
    noteContentData.title = note.title;
    noteContentData.isTopping = note.topping;
    noteContentData.imageUrl = note.imageUrl;
    noteContentData.userId = user.id;
    noteContentData.text = note.content;
    noteContentData.createTime = note.createTime;
    noteContentData.isPublic = user.id === '22' ? 1 : 0;
    noteContentData.noteUsername = user.username ? user.username : '旅行者';
    this.noteRepository.save(noteContentData);
    return CommonResult(null, true, 200, '文章已录用');
  }
  async update(noteParams: any) {
    const noteContentData = await this.noteRepository.findOne({
      where: { id: noteParams.noteId },
    });

    noteContentData.text = noteParams.content;
    noteContentData.isTopping = noteParams.topping || false;
    this.noteRepository.save(noteContentData);
  }
  async setLikes(commentId: any) {
    // 这里需要判断用户是否已经点赞
    const userLikeCount: any = await this.noteRepository.findOne({
      where: { id: commentId },
      select: ['like'],
    });
    let count = userLikeCount.like;
    count++;
    const result = this.noteRepository.update(commentId, {
      like: count,
    });
    return result;
  }

  async setSees(noteId: any) {
    const userLikeCount: any = await this.noteRepository.findOne({
      where: { id: noteId },
      select: ['see'],
    });
    let count = userLikeCount.see;
    count++;
    const result = this.noteRepository.update(noteId, {
      see: count,
    });
    return result;
  }

  async deleteNotes(note: any) {
    console.info(note);
    if (note.imageUrl != '') {
      try {
        unlinkSync(join(__dirname, `../../public/images/${note.imageUrl}`));
      } catch (err) {
        console.info('没有此图片，删除失败');
      }
    }
    const result = await this.noteRepository.delete(note.noteId);
    return result;
  }

  async findNote(noteId: any) {
    const noteContentData = await this.noteRepository.findOne({
      where: { id: noteId },
    });
    return noteContentData;
  }

  async setIsPublic(note: any) {
    const noteData = await this.noteRepository.findOne({
      where: { id: note.noteId },
    });
    noteData.userId = note.isPublic === 0 ? '0' : '22';
    noteData.isPublic = note.isPublic;
    const result = await this.noteRepository.save(noteData);
    return result;
  }
}
